//
//  WJPlaceholderTextView.m
//  BaiSiBuDeJie
//
//  Created by jerrywang on 2017/10/15.
//  Copyright © 2017年 王军. All rights reserved.
//

#import "WJPlaceholderTextView.h"

@implementation WJPlaceholderTextView

- (instancetype) initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        //设置默认字体
        self.font = [UIFont systemFontOfSize:15];
        //设置默认颜色
        self.placeholderColor = [UIColor grayColor];
        //监听文字改变
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
    }
    
    return self;
}

- (void)dealloc {
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void) textDidChange: (NSNotification *)notification {
    //重新调用drawRect:方法
    [self setNeedsDisplay];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    [self setNeedsDisplay];
}

//每次调用drawRect:方法前，都会将以前画的东西清除掉
- (void)drawRect:(CGRect)rect {
    
    //如果有文字，则直接返回，不需要画占位文字
    if (self.hasText) {
        return;
    }
    
    //属性
    NSMutableDictionary *attrsDic = [NSMutableDictionary dictionary];
    attrsDic[NSFontAttributeName] = self.font;
    attrsDic[NSForegroundColorAttributeName] = self.placeholderColor;
    
    //画文字
    rect.origin.x = 5;
    rect.origin.y = 8;
    rect.size.width -= 2 * rect.origin.x;
    [self.placeholderText drawInRect:rect withAttributes:attrsDic];
}

#pragma mark setter方法
- (void)setPlaceholderText:(NSString *)placeholderText {
    _placeholderText = [placeholderText copy];
    [self setNeedsDisplay];
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor {
    _placeholderColor = [placeholderColor copy];
    [self setNeedsDisplay];
}

- (void)setFont:(UIFont *)font {
    [super setFont:font];
    [self setNeedsDisplay];
}

- (void)setText:(NSString *)text {
    [super setText:text];
    [self setNeedsDisplay];
}

- (void)setAttributedText:(NSAttributedString *)attributedText {
    [super setAttributedText:attributedText];
    [self setNeedsDisplay];
}

@end
